'use client';

import { useState, useEffect, useMemo } from 'react';
import { useParams } from 'next/navigation';
import { useSession } from 'next-auth/react';
import AppHeader from '@/components/ui/app-header';
import { projectApi } from '@/lib/api';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Skeleton } from '@/components/ui/skeleton';
import {
  CalendarIcon,
  ClockIcon,
  UserCircleIcon,
  CheckCircleIcon,
  PencilIcon,
  PlusCircleIcon,
  TagIcon,
  ChatBubbleLeftRightIcon,
  ArrowPathIcon,
  ArchiveBoxIcon
} from '@heroicons/react/24/outline';
import { cn } from '@/lib/utils';

// 活动类型
type ActivityType = 
  | 'TASK_CREATED'
  | 'TASK_UPDATED'
  | 'TASK_COMPLETED'
  | 'COMMENT_ADDED'
  | 'MEMBER_ADDED'
  | 'MEMBER_REMOVED'
  | 'PROJECT_CREATED'
  | 'PROJECT_UPDATED'
  | 'TAG_ADDED'
  | 'TAG_REMOVED'
  | 'STATUS_CHANGED';

// 活动记录类型
interface Activity {
  id: string;
  type: ActivityType;
  userId: string;
  projectId: string;
  taskId?: string;
  entityId?: string;
  createdAt: string;
  meta?: {
    status?: string;
    oldStatus?: string;
    task?: {
      title: string;
    };
    user?: {
      name: string;
    };
    tags?: string[];
    comment?: string;
  };
  data?: {
    status?: string;
    oldStatus?: string;
    task?: {
      title: string;
    };
    user?: {
      name: string;
    };
    tags?: string[];
    comment?: string;
  };
  user: {
    id: string;
    name: string;
    image?: string;
  };
}

// 项目类型
interface Project {
  id: string;
  name: string;
  description?: string;
}

export default function ProjectActivityPage() {
  const { id } = useParams<{ id: string }>();
  const { data: session, status } = useSession();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [project, setProject] = useState<Project | null>(null);
  const [activities, setActivities] = useState<Activity[]>([]);
  const [filter, setFilter] = useState<string>('all');

  // 获取项目和活动记录
  useEffect(() => {
    const fetchProjectData = async () => {
      if (status !== 'authenticated' || !id) return;
      
      setLoading(true);
      setError(null);
      
      try {
        // 获取项目详情
        const projectData = await projectApi.getProject(id as string);
        setProject(projectData);
        
        // 获取项目活动
        const activitiesData = await projectApi.getProjectActivities(id as string);
        
        // 确保活动数据是数组
        if (Array.isArray(activitiesData)) {
          setActivities(activitiesData);
        } else if (activitiesData && Array.isArray(activitiesData.data)) {
          // 如果API返回格式是 { data: [...] }
          setActivities(activitiesData.data);
        } else {
          console.warn('活动数据格式不符合预期:', activitiesData);
          setActivities([]); // 设置为空数组避免错误
        }
      } catch (err) {
        console.error('获取项目数据失败:', err);
        setError('无法加载项目数据，请重试');
      } finally {
        setLoading(false);
      }
    };
    
    fetchProjectData();
  }, [id, status]);

  // 格式化日期
  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // 根据活动类型获取图标
  const getActivityIcon = (type: ActivityType) => {
    switch (type) {
      case 'TASK_CREATED':
        return <PlusCircleIcon className="w-5 h-5 text-green-500" />;
      case 'TASK_UPDATED':
        return <PencilIcon className="w-5 h-5 text-blue-500" />;
      case 'TASK_COMPLETED':
        return <CheckCircleIcon className="w-5 h-5 text-green-600" />;
      case 'COMMENT_ADDED':
        return <ChatBubbleLeftRightIcon className="w-5 h-5 text-purple-500" />;
      case 'MEMBER_ADDED':
      case 'MEMBER_REMOVED':
        return <UserCircleIcon className="w-5 h-5 text-blue-500" />;
      case 'PROJECT_CREATED':
      case 'PROJECT_UPDATED':
        return <ArchiveBoxIcon className="w-5 h-5 text-indigo-500" />;
      case 'TAG_ADDED':
      case 'TAG_REMOVED':
        return <TagIcon className="w-5 h-5 text-yellow-500" />;
      case 'STATUS_CHANGED':
        return <ArrowPathIcon className="w-5 h-5 text-orange-500" />;
      default:
        return <ClockIcon className="w-5 h-5 text-gray-500" />;
    }
  };

  // 根据活动类型获取描述
  const getActivityDescription = (activity: Activity) => {
    const { type, meta, data, user } = activity;
    const userName = user?.name || '未知用户';
    // 兼容不同格式，meta可能是undefined，而实际数据在data字段中
    const metaData = meta || data || {};
    
    switch (type) {
      case 'TASK_CREATED':
        return (
          <span>
            <span className="font-medium">{userName}</span> 创建了任务 
            <span className="font-medium">{metaData?.task?.title || '未知任务'}</span>
          </span>
        );
      case 'TASK_UPDATED':
        return (
          <span>
            <span className="font-medium">{userName}</span> 更新了任务 
            <span className="font-medium">{metaData?.task?.title || '未知任务'}</span>
          </span>
        );
      case 'TASK_COMPLETED':
        return (
          <span>
            <span className="font-medium">{userName}</span> 完成了任务 
            <span className="font-medium">{metaData?.task?.title || '未知任务'}</span>
          </span>
        );
      case 'COMMENT_ADDED':
        return (
          <span>
            <span className="font-medium">{userName}</span> 在任务 
            <span className="font-medium">{metaData?.task?.title || '未知任务'}</span> 上添加了评论：
            <span className="italic text-gray-600">"{metaData?.comment || ''}"</span>
          </span>
        );
      case 'MEMBER_ADDED':
        return (
          <span>
            <span className="font-medium">{userName}</span> 添加了 
            <span className="font-medium">{metaData?.user?.name || '未知用户'}</span> 到项目团队
          </span>
        );
      case 'MEMBER_REMOVED':
        return (
          <span>
            <span className="font-medium">{userName}</span> 将 
            <span className="font-medium">{metaData?.user?.name || '未知用户'}</span> 从项目团队中移除
          </span>
        );
      case 'PROJECT_CREATED':
        return (
          <span>
            <span className="font-medium">{userName}</span> 创建了项目
          </span>
        );
      case 'PROJECT_UPDATED':
        return (
          <span>
            <span className="font-medium">{userName}</span> 更新了项目信息
          </span>
        );
      case 'TAG_ADDED':
        return (
          <span>
            <span className="font-medium">{userName}</span> 添加了标签：
            {metaData?.tags?.map((tag, index) => (
              <span key={index} className="inline-flex items-center ml-1 px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-800">
                {tag}
              </span>
            ))}
          </span>
        );
      case 'TAG_REMOVED':
        return (
          <span>
            <span className="font-medium">{userName}</span> 移除了标签：
            {metaData?.tags?.map((tag, index) => (
              <span key={index} className="inline-flex items-center ml-1 px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-800">
                {tag}
              </span>
            ))}
          </span>
        );
      case 'STATUS_CHANGED':
        return (
          <span>
            <span className="font-medium">{userName}</span> 将任务 
            <span className="font-medium">{metaData?.task?.title || '未知任务'}</span> 的状态从 
            <span className="font-medium">{metaData?.oldStatus || '未知'}</span> 改为 
            <span className="font-medium">{metaData?.status || '未知'}</span>
          </span>
        );
      default:
        return <span><span className="font-medium">{userName}</span> 执行了操作</span>;
    }
  };

  // 过滤活动记录
  const filteredActivities = useMemo(() => {
    // 确保activities是数组
    if (!Array.isArray(activities)) {
      console.warn('activities不是数组:', activities);
      return [];
    }
    
    if (filter === 'all') {
      return activities;
    }
    
    return activities.filter(activity => {
      // 确保activity和type存在
      if (!activity || typeof activity.type !== 'string') {
        return false;
      }
      
      try {
        return activity.type.toLowerCase().includes(filter.toLowerCase());
      } catch (error) {
        console.error('过滤活动出错:', error);
        return false;
      }
    });
  }, [activities, filter]);

  // 渲染活动时间线
  const renderTimeline = () => {
    // 确保filteredActivities是数组
    if (!Array.isArray(filteredActivities) || filteredActivities.length === 0) {
      return (
        <div className="flex justify-center items-center h-40">
          <p className="text-gray-500">暂无活动记录</p>
        </div>
      );
    }

    return filteredActivities.map((activity, index) => (
      <div key={activity.id || index} className="relative pb-8">
        {index < filteredActivities.length - 1 && (
          <span
            className="absolute top-5 left-5 -ml-px h-full w-0.5 bg-gray-200"
            aria-hidden="true"
          />
        )}
        <div className="relative flex items-start space-x-3">
          <div>
            <div className="relative px-1">
              <div className="flex h-8 w-8 items-center justify-center rounded-full bg-gray-100 ring-8 ring-white">
                {getActivityIcon(activity.type)}
              </div>
            </div>
          </div>
          <div className="min-w-0 flex-1">
            <div className="text-sm">
              <div className="font-medium text-gray-900">
                {getActivityDescription(activity)}
              </div>
              <div className="mt-0.5 text-gray-500 flex items-center space-x-2">
                <CalendarIcon className="h-4 w-4" />
                <span>{formatDate(activity.createdAt)}</span>
              </div>
            </div>
            <div className="mt-2 flex items-center space-x-2">
              <Avatar className="h-6 w-6">
                <AvatarImage src={activity.user?.image || ''} alt={activity.user?.name || ''} />
                <AvatarFallback>
                  {activity.user?.name 
                    ? activity.user.name.substring(0, 2).toUpperCase() 
                    : 'UN'}
                </AvatarFallback>
              </Avatar>
              <span className="text-sm text-gray-500">{activity.user?.name || '未知用户'}</span>
            </div>
          </div>
        </div>
      </div>
    ));
  };

  if (loading) {
    return (
      <div className="container py-6">
        <div className="space-y-8">
          <Skeleton className="h-10 w-3/4" />
          <div className="space-y-6">
            <div className="flex space-x-4">
              <Skeleton className="h-10 w-10 rounded-full" />
              <div className="space-y-2 flex-1">
                <Skeleton className="h-4 w-full" />
                <Skeleton className="h-4 w-3/4" />
              </div>
            </div>
            <div className="flex space-x-4">
              <Skeleton className="h-10 w-10 rounded-full" />
              <div className="space-y-2 flex-1">
                <Skeleton className="h-4 w-full" />
                <Skeleton className="h-4 w-3/4" />
              </div>
            </div>
            <div className="flex space-x-4">
              <Skeleton className="h-10 w-10 rounded-full" />
              <div className="space-y-2 flex-1">
                <Skeleton className="h-4 w-full" />
                <Skeleton className="h-4 w-3/4" />
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="container py-6">
        <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded relative">
          <strong className="font-bold">错误：</strong>
          <span className="block sm:inline">{error}</span>
        </div>
      </div>
    );
  }

  return (
    <div className="container py-6">
      <AppHeader
        title={project?.name ? `${project.name} - 活动记录` : '项目活动'}
        subtitle="查看项目团队的所有操作历史"
        actions={
          <div className="flex">
            <select
              className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
              value={filter}
              onChange={(e) => setFilter(e.target.value)}
              aria-label="筛选活动类型"
            >
              <option value="all">所有活动</option>
              <option value="task">任务相关</option>
              <option value="member">团队成员</option>
              <option value="comment">评论</option>
              <option value="project">项目更新</option>
            </select>
          </div>
        }
      />
      
      <div className="mt-6 flow-root">
        <div className="overflow-hidden bg-white shadow sm:rounded-md">
          <div className="p-6">
            <ul className="-mb-8">
              {renderTimeline()}
            </ul>
          </div>
        </div>
      </div>
    </div>
  );
} 